using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.ComponentModel;

namespace VariationsEnabledContentByQueryWebPart.WebPartCode
{
    [Guid("daffbc68-6731-4007-a4c5-98fe67727e11")]
    public class VariationsEnabledContentByQueryWebPart : Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart
    {
        private bool _error = false;

        private bool variationsEnabled;

        [Personalizable(PersonalizationScope.Shared), DefaultValue(false), WebBrowsable(false)]
        public bool VariationsEnabled
        {
            get { return variationsEnabled; }
            set { variationsEnabled = value; }
        }

        public string GetVariationLabelWebUrl(Microsoft.SharePoint.Publishing.VariationLabel label)
        {
            // Find the sourcelabel
            Microsoft.SharePoint.Publishing.VariationLabel sourcelabel = null;
            foreach (Microsoft.SharePoint.Publishing.VariationLabel ual in Microsoft.SharePoint.Publishing.Variations.Current.UserAccessibleLabels)
            {
                if (ual.IsSource) sourcelabel = ual;
            }

            if (sourcelabel != null)
            {
                // Split the url and replace
                string[] splittedurl = WebUrl.Split('/');
                if (splittedurl.Length >= 2 && string.Compare(sourcelabel.Title, splittedurl[1], true) == 0)
                {
                    splittedurl[1] = label.Title;
                    return string.Join("/", splittedurl);
                }
            }

            return WebUrl;
        }



        public VariationsEnabledContentByQueryWebPart()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                {

                    base.CreateChildControls();

                    if (VariationsEnabled)
                    {
                        if (!string.IsNullOrEmpty(this.WebUrl) && Microsoft.SharePoint.Publishing.PublishingWeb.IsPublishingWeb(Microsoft.SharePoint.SPContext.Current.Web))
                        {
                            Microsoft.SharePoint.Publishing.PublishingWeb cpweb = Microsoft.SharePoint.Publishing.PublishingWeb.GetPublishingWeb(Microsoft.SharePoint.SPContext.Current.Web);
                            if (cpweb != null && cpweb.Label != null)
                            {
                                if (string.IsNullOrEmpty(this.ListGuid) && string.IsNullOrEmpty(this.ListName))
                                {
                                    this.WebUrl = GetVariationLabelWebUrl(cpweb.Label);
                                }
                                else
                                {
                                    string VarWebUrl = GetVariationLabelWebUrl(cpweb.Label);
                                    Microsoft.SharePoint.SPWeb web = Microsoft.SharePoint.SPContext.Current.Site.OpenWeb(VarWebUrl);
                                    Microsoft.SharePoint.SPList list = null;
                                    try
                                    {
                                        list = web.Lists[this.ListGuid];
                                    }
                                    catch (Exception)
                                    { }

                                    if (list == null)
                                    {
                                        try
                                        {
                                            list = web.Lists[this.ListName];
                                        }
                                        catch (Exception)
                                        { }
                                    }

                                    // Does the list exist in the variation web?
                                    if (list != null)
                                    { // Yes
                                        this.ListGuid = list.ID.ToString();
                                        this.WebUrl = VarWebUrl;
                                    }
                                }
                            }
                            cpweb.Close();
                        }
                    }

                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        public override EditorPartCollection CreateEditorParts()
        {
            System.Collections.Generic.List<EditorPart> editorparts = new System.Collections.Generic.List<EditorPart>();

            VariationsEnabledContentByQueryEditorPart vecbqep = new VariationsEnabledContentByQueryEditorPart();
            vecbqep.ID = "becbqep";
            editorparts.Add(vecbqep);

            return new EditorPartCollection(base.CreateEditorParts(), editorparts);
        }


        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }
    }
}
